package cn.rubintry.bug.hunting.activity


import android.Manifest
import android.os.Handler
import android.os.Looper
import androidx.activity.addCallback
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import cn.rubintry.bug.common.base.BaseActivity
import cn.rubintry.bug.hunting.databinding.ActivityMainBinding
import cn.rubintry.bug.hunting.common.event.MoveToFirstTabEvent
import cn.rubintry.bug.hunting.common.extension.toObject
import cn.rubintry.bug.hunting.fragment.DiscoverFragment
import cn.rubintry.bug.hunting.fragment.MineFragment
import cn.rubintry.bug.hunting.common.http.viewmodel.AppViewModel
import cn.rubintry.bug.hunting.common.utils.OkhttpDownloadUtils
import cn.rubintry.bug.hunting.common.utils.OkhttpDownloadUtils.DownloadListener
import cn.rubintry.bug.ui.components.pojo.AppUpdateMsgModel
import cn.rubintry.bug.ui.components.AppUpdateDialog
import cn.rubintry.bug.hunting.viewpager.HomeViewPagerAdapter
import cn.rubintry.bug.lib.umeng.UmengInitializer
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PathUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.TabLayoutOnPageChangeListener
import org.greenrobot.eventbus.EventBus
import java.io.File


/**
 * 主页
 */
class MainActivity : BaseActivity<ActivityMainBinding>() {

    private val appViewModel : AppViewModel by viewModels<AppViewModel>()

    private var viewPagerAdapter: HomeViewPagerAdapter? = null

    /**
     * 上一次返回键按下的时间
     */
    private var backPressTimeMills = 0L

    override fun bindingClazz(): Class<ActivityMainBinding> {
        return ActivityMainBinding::class.java
    }

    override fun getActivityParams() {

    }


    override fun initView() {
        binding.vpHome.offscreenPageLimit = 3
        val fragmentList = mutableListOf<Fragment>(
            DiscoverFragment(),
            MineFragment()
        )
        viewPagerAdapter = HomeViewPagerAdapter(
            fragmentList,
            supportFragmentManager,
            FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        )
        binding.vpHome.adapter = viewPagerAdapter
        viewPagerAdapter?.notifyDataSetChanged()
        binding.vpHome.addOnPageChangeListener(TabLayoutOnPageChangeListener(binding.tabHome))
        binding.tabHome.addOnTabSelectedListener(AbsOnTabSelectedListener())
        binding.tabHome.addTab(binding.tabHome.newTab().setText("发现"))
        binding.tabHome.addTab(binding.tabHome.newTab().setText("我的"))

        //返回键监听
        onBackPressedDispatcher.addCallback {
            if (binding.vpHome.currentItem != 0) {
                binding.vpHome.currentItem = 0
                return@addCallback
            }
            val currentMillSecond = System.currentTimeMillis()
            if (currentMillSecond - backPressTimeMills > 2000) {
                backPressTimeMills = currentMillSecond
                ToastUtils.showShort("再按一次退出程序")
            } else {
                finish()
            }
        }

        PermissionUtils.permission(Manifest.permission.REQUEST_INSTALL_PACKAGES)
            .request()


        binding?.mainSplash?.startAnimation(){
            appViewModel.checkVersion()
        }


        //TODO 这里假设用户同意了消息推送
        UmengInitializer.setAgree(true)
    }




    override fun observeData() {
        appViewModel.versionData.observe(this){data ->
            if(data.code == "0"){
                data?.data?.let {
                    if(it.appVersion > AppUtils.getAppVersionName()){
                        AppUpdateDialog.Builder(this)
                            .setTitle("发现新版本")
                            .setMsgList(it.msgListJson.toObject<List<AppUpdateMsgModel>>())
                            .setFileSize(it.fileSize.toLong())
                            .setOnUpgradeClick { dialog ->
                                val dir = File(PathUtils.getExternalAppDataPath())
                                if (!dir.exists()) {
                                    dir.mkdirs()
                                }
                                val apkFile = File(dir, "BugHunting_${it.appVersion}.apk")
                                if (!apkFile.exists()) {
                                    apkFile.createNewFile()
                                }
                                OkhttpDownloadUtils.downloadFile(data.data?.url ?: "", apkFile.absolutePath, object : DownloadListener{
                                    override fun onProgress(progress: Int) {
                                        Handler(Looper.getMainLooper()).post {
                                            dialog.updateProgress(progress)
                                        }
                                    }

                                    override fun onFinish(apkFile: File?) {
                                        AppUtils.installApp(apkFile)
                                        Handler(Looper.getMainLooper()).post {
                                            dialog.complete()
                                        }
                                    }

                                })
                            }
                            .create()
                            .show()
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        OkhttpDownloadUtils.clearTask()
    }

    override fun onNetWorkError(msg: String?) {

    }


    inner class AbsOnTabSelectedListener : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            binding.vpHome.currentItem = tab?.position ?: 0

        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {

        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
            if (tab?.position == 0) {
                EventBus.getDefault().post(MoveToFirstTabEvent())
            }
        }

    }


}
